<template>
  <div class="add-dialog-container">
    <el-skeleton :rows="5" animated v-if="loading" />
    <div v-else class="add-dialog-content">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <template
          v-for="(group, groupIndex) in groupedColumns"
          :key="groupIndex"
        >
          <el-descriptions
            :column="
              group.length === 1 && group[0].editType === 'textarea' ? 1 : 2
            "
            :border="true"
            size="medium"
            class="add-descriptions"
          >
            <template v-for="(column, index) in group" :key="index">
              <el-descriptions-item
                :label="column.attributeLabel"
                label-class-name="detail-label"
                content-class-name="detail-value"
              >
                <el-form-item
                  :prop="column.attributeName"
                  :rules="column.rules"
                >
                  <el-input
                    v-if="column.editType === 'text'"
                    v-model="addForm[column.attributeName]"
                    :placeholder="'请输入' + column.attributeLabel"
                    clearable
                  />

                  <el-select
                    v-else-if="column.editType === 'select'"
                    v-model="addForm[column.attributeName]"
                    :placeholder="'请选择' + column.attributeLabel"
                    clearable
                    filterable
                    style="width: 100%"
                  >
                    <!-- 选项渲染 -->
                    <el-option
                      v-for="option in column.selectOperation?.options || []"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                      :disabled="option.disabled"
                    />
                    
                  </el-select>

                  <el-input
                    v-else-if="column.editType === 'password'"
                    v-model="addForm[column.attributeName]"
                    type="password"
                    :placeholder="'请输入' + column.attributeLabel"
                    clearable
                  />


                  <el-input
                  v-if="column.editType === 'number'" 
                  v-model="addForm[column.attributeName]"
                  :placeholder="column.attributeTooltip"
                  clearable
                  style="width: 100%; min-width: 120px"
                  @input="onNumberInput(column.attributeName,/\D/g)"
                ></el-input>

                  <el-input
                    v-else-if="column.editType === 'email'"
                    v-model="addForm[column.attributeName]"
                    type="email"
                    :placeholder="'请输入' + column.attributeLabel"
                    clearable
                  />
                  <el-input
                    v-else-if="column.editType === 'url'"
                    v-model="addForm[column.attributeName]"
                    type="url"
                    :placeholder="'请输入' + column.attributeLabel"
                    clearable
                  />
                  <el-date-picker
                    v-else-if="column.editType === 'date'"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" 
                    v-model="addForm[column.attributeName]"
                    type="date"
                    :placeholder="'请选择' + column.attributeLabel"
                    clearable
                  />
                  <el-date-picker
                    v-else-if="column.editType === 'datetime-local'"
                    v-model="addForm[column.attributeName]"
                    type="datetime-local"
                    :placeholder="'请选择' + column.attributeLabel"
                    clearable
                  />
                  <el-date-picker
                    v-else-if="column.editType === 'month'"
                    v-model="addForm[column.attributeName]"
                    type="month"
                    :placeholder="'请选择' + column.attributeLabel"
                    clearable
                  />
                  <el-date-picker
                    v-else-if="column.editType === 'week'"
                    v-model="addForm[column.attributeName]"
                    type="week"
                    :placeholder="'请选择' + column.attributeLabel"
                    clearable
                  />
                  <el-time-picker
                    v-else-if="column.editType === 'time'"
                    v-model="addForm[column.attributeName]"
                    :placeholder="'请选择' + column.attributeLabel"
                    clearable
                  />
                  <el-color-picker
                    v-else-if="column.editType === 'color'"
                    v-model="addForm[column.attributeName]"
                    :predefine-colors="[]"
                  />
                  <el-input
                    v-else-if="column.editType === 'textarea'"
                    v-model="addForm[column.attributeName]"
                    type="textarea"
                    :rows="4"
                    :placeholder="'请输入' + column.attributeLabel"
                  />
                </el-form-item>
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </template>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="$emit('closeDialog')">取消</el-button>
        <el-button type="primary" @click="confirmSave">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, computed } from "vue";
import axios from "axios";
import { MainAttributeInfoInterface } from "@/views/common/ts/Interface";
import { ElMessage, ElForm, ElMessageBox } from "element-plus";
import {filterInputByPattern} from '@/views/common/ts/EditFunction';

const props = defineProps<{
  addUrl: string; // 新增接口地址
  tableColumnList: MainAttributeInfoInterface[]; // 表格列配置
}>();
const emits = defineEmits(["closeDialog", "addSuccess"]);

const addForm = ref<Record<string, any>>({}); // 新增表单数据
const loading = ref(false); // 加载状态
const addFormRef = ref<InstanceType<typeof ElForm>>();

// 过滤出需要显示在新增表单中的列
const validColumns = computed(() => {
  return props.tableColumnList.filter((column) => !column.unInsertable);
});

// 初始化表单数据
validColumns.value.forEach((column) => {
  addForm.value[column.attributeName] = column.addDefaultValue || "";
});

// 对列进行分组
const groupedColumns = computed(() => {
  const groups = [];
  let currentGroup = [];
  for (const column of validColumns.value) {
    if (column.editType === "textarea") {
      if (currentGroup.length > 0) {
        groups.push(currentGroup);
        currentGroup = [];
      }
      groups.push([column]);
    } else {
      currentGroup.push(column);
      if (currentGroup.length === 2) {
        groups.push(currentGroup);
        currentGroup = [];
      }
    }
  }
  if (currentGroup.length > 0) {
    groups.push(currentGroup);
  }
  return groups;
});

const onNumberInput = (key: string, pattern: RegExp) => {
  filterInputByPattern(addForm.value, key,pattern);
};


// 确认保存
const confirmSave = async () => {
  if (addFormRef.value) {
    await addFormRef.value.validate((valid) => {
      if (valid) {
        ElMessageBox.confirm("确定要保存新增内容吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            saveChanges();
          })
          .catch(() => {});
      } else {
        ElMessage.error("表单验证失败，请检查输入内容");
      }
    });
  }
};

// 保存修改
const saveChanges = async () => {
  try {
    loading.value = true;
    const response = await axios.post(props.addUrl, addForm.value);
    if (response.data && response.data.result) {
      ElMessage.success("新增成功!!!!");
      // 这里添加调试日志
      console.log("新增成功，准备触发关闭对话框和成功事件");
      emits("closeDialog");
      emits("addSuccess");
    } else {
      ElMessage.error(response.data.msg || "新增失败");
      console.log("新增失败，错误信息:", response.data.msg || "新增失败");
    }
  } catch (err: any) {
    ElMessage.error(err.message || "新增失败");
    console.log("捕获到异常，错误信息:", err.message || "新增失败");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.add-dialog-container {
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  max-width: 800px;
  margin: 0 auto;
}

.add-dialog-content {
  margin-top: 8px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: center;
}

.close-button {
  width: 100px;
}

.save-button {
  width: 100px;
  margin-right: 20px;
}

.el-input,
.el-textarea,
.el-date-picker,
.el-time-picker,
.el-color-picker {
  width: 100%;
}

.detail-label {
  color: #909399 !important;
  background-color: #f5f7fa !important;
  width: 160px;
  padding: 12px 10px !important;
  line-height: 1.5;
  word-break: break-word;
  white-space: normal;
  vertical-align: top;
}

.detail-value {
  color: #606266;
  padding: 12px 10px !important;
  line-height: 1.5;
  min-width: 200px;
}

.el-descriptions__body .el-descriptions__table {
  table-layout: fixed;
}

.el-descriptions__body .el-descriptions__table td {
  word-break: break-word;
}
</style>